package crawler.web.engine.custom;

import javax.annotation.Resource;

import library.database.mongo.MongoDB;

import org.springframework.stereotype.Component;

import crawler.web.beans.CrawlPageContext;
import crawler.web.engine.config.SpBN;
import crawler.web.engine.config.Suite.ParseStatus;

/**
 * @author waynechen Mar 11, 2012 7:51:21 PM
 */
@Component("MongoDBAdapter")
public class MongoDBAdapter {

	@Resource(name = SpBN.bean_MongoDB)
	private MongoDB mongo;
	private int index = 0;

	public synchronized CrawlPageContext getNext(String tableName, ParseStatus from, ParseStatus to) {
		//查找一个状态为下载的记录
		CrawlPageContext query = new CrawlPageContext();
		query.setParseStatus(from.getValue());
		CrawlPageContext context = mongo.findOne(tableName, query);

		//没有查到
		if (context == null)
			return null;

		//更新状态
		//		query = new CrawlPageContext();
		//		query.set_id(context.get_id());
		context.setParseStatus(to.getValue());
		//		mongo.update(tableName, query, context);
		mongo.update(tableName,//
				String.format("{'_id':{'$oid':'%s'}}", context.get_id().get$oid()),//
				String.format("{$set:{'parseStatus':%d}}", to.getValue()),//
				false, false);
		return context;
	}

	public synchronized CrawlPageContext getNext(String tableName) {
		CrawlPageContext context = mongo.findOneByIndex(tableName, CrawlPageContext.class, index);
		if (context != null)
			index++;
		return context;
	}

}
//	private CrawlPageContext lastOne;
//	private String query = "{'_id' : {'$gt' : {'$oid' : '%s'}}}";
//		if (lastOne == null)
//			page = lastOne = mongo.findOne(tableName, CrawlPageContext.class);
//		else {
//			page = mongo.findOne(String.format(query, lastOne.get_id().get$oid()), tableName, CrawlPageContext.class);
//			if (page != null)
//				lastOne = page;
//		}
//
//
//
//
//
//
//
//
//
//
//